package com.blockmeta.bbs.immodule.corebean.Impl;

import android.annotation.SuppressLint;
import android.content.Context;
import androidx.annotation.NonNull;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;

import com.blockmeta.bbs.baselibrary.net.callback.BaseResponseCallBack;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.expiringmap.ExpiringMap;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.Constants;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.beaninterface.ICircleEntry;
import com.blockmeta.bbs.immodule.corebean.ICircleDomainService;
import com.blockmeta.bbs.immodule.corebean.IDomainCommonManger;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.INoticeManager;
import com.blockmeta.bbs.immodule.dao.CircleMember;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.greendao.repository.IUserRepo;
import com.blockmeta.bbs.immodule.net.api.CircleDetailApi;
import com.blockmeta.bbs.immodule.net.api.CircleMemberApi;
import com.blockmeta.bbs.immodule.net.api.JoinCircleApi;
import com.blockmeta.bbs.immodule.net.pojo.CircleDetailResponse;
import com.blockmeta.bbs.immodule.net.pojo.CircleMemberResponse;
import com.blockmeta.bbs.immodule.net.pojo.Notice;
import com.blockmeta.bbs.immodule.utils.IMUtils;
import com.blockmeta.bbs.immodule.widget.IMAddCircleMsg;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import rx.functions.Action1;


/**
 * 一些圈子业务逻辑的封装
 */
public class CircleDomainService implements ICircleDomainService {
    final Context mContext;
    IUserRepo userRepo;
    IDomainCommonManger domainCommonManger;
    INoticeManager noticeManager;

    //会过期的map，避免每次重复调用http
    Map<Long, Notice> noticeMap = ExpiringMap.builder().maxSize(100).expiration(120, TimeUnit.SECONDS).build();
    Map<Long, List<CircleMemberResponse>> circleMemberMap = ExpiringMap.builder().maxSize(100).expiration(200, TimeUnit.SECONDS).build();


    public CircleDomainService(Context context) {
        mContext = context;
        userRepo = IMRepoContext.getIMUserRepo(context);
        domainCommonManger = IMApplicationContext.getDomainCommonManger();
        noticeManager = new NoticeManager();
    }

    @Override
    public void getGroup(long groupId, final BaseResponseCallBack<String, IMUserEntity> callBack) {
        IMUserEntity user = getUser(groupId);
        if (user != null) {
            callBack.success(user);
        } else {
            RetrofitFactory.getRetrofit().create(CircleDetailApi.class)
                    .circleDetail(groupId, AccountHelper.getUidInt())
                    .compose(RxUtil.<BaseImResponse<CircleDetailResponse>>rxSchedulerHelper())
                    .compose(RxUtil.<CircleDetailResponse>commonResult())
                    .subscribe(new CommonSubscriber<CircleDetailResponse>(mContext) {
                        @Override
                        public void onNext(CircleDetailResponse circleDetailResponse) {

                            IMUserEntity IMUserEntity = saveImUserEntityByCircleResponse(circleDetailResponse);
                            callBack.success(IMUserEntity);
                        }


                        @Override
                        public void onError(Throwable t) {
                            //如果圈子被解散了，会进入error
                            callBack.fail(t.getMessage());
                            LogUtils.d("author" + "getgroup error" + t.getMessage());
                        }
                    });

        }


    }

    @Override
    @NonNull
    public IMUserEntity saveImUserEntityByCircleResponse(CircleDetailResponse circleDetailResponse) {
        IMUserEntity IMUserEntity = new IMUserEntity();
        IMUserEntity.setRemarkName(circleDetailResponse.name);
        IMUserEntity.setUserId(circleDetailResponse.id);
        IMUserEntity.setAvatarPath(circleDetailResponse.groupLogo);
        IMUserEntity.setWhoId(AccountHelper.getUidInt());
        IMUserEntity.setCircleClass(circleDetailResponse.bigClassId);
        IMUserEntity.setName(circleDetailResponse.name);
        IMUserEntity.setType(Params.USER_GROUP);
        IMUserEntity.setIdentification(circleDetailResponse.identification);
        IMUserEntity.setCreateUserId(circleDetailResponse.createById);
        if (circleDetailResponse.isMeIn) {
            IMUserEntity userEntity = userRepo.addAndUpdateUser(AccountHelper.getUidInt(), IMUserEntity);
            return userEntity;
        }
        return IMUserEntity;
    }


    @Override
    public void deleteCircle(long mCircleId) {
        IMUserEntity circle = userRepo.getUser(AccountHelper.getUidInt(), mCircleId, Params.USER_GROUP);
        if(circle != null){
            userRepo.delete(circle);
        }
    }


    @Override
    public void joinCircle(Context context, final long circleId, int circleAuthRule, int userLevel, final CircleJoinCallBack circleJoinCallBack) {
        if (circleAuthRule == 0) {
            ProgressBarUtil.showProgress(context);
            RetrofitFactory.getRetrofit().create(JoinCircleApi.class)
                    .joinCircle(circleId, AccountHelper.getUidInt(), "")
                    .compose(RxUtil.<BaseImResponse<Object>>rxSchedulerHelper())
                    .compose(RxUtil.<Object>commonResult())
                    .compose(((RxAppCompatActivity) context).<Object>bindToLifecycle())
                    .subscribe(new CommonSubscriber<Object>(context) {
                        @Override
                        public void onNext(Object o) {
                            getGroup(circleId, new BaseResponseCallBack<String, IMUserEntity>() {
                                @Override
                                public void fail(String msg) {
                                    if (circleJoinCallBack != null) {
                                        circleJoinCallBack.onFail();
                                    }
                                }

                                @Override
                                public void success(IMUserEntity imUserEntity) {
                                    if (circleJoinCallBack != null) {
                                        circleJoinCallBack.onSuccess("成功");
                                    }
                                    IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_AddCircles());
                                }
                            });

                        }

                        @Override
                        public void onError(Throwable t) {
                            super.onError(t);
                            if (circleJoinCallBack != null) {
                                circleJoinCallBack.onFail();
                            }
                        }
                    });

        } else {
//            int groupid = AccountHelper.getUserPhonePOJO().getGroupIdInt();
//            //userlevel是圈子用户等级
//            if (userLevel > 0 && groupid > 0) {
//                boolean matchLevel = IMUtils.UserLevel.matchLevel(groupid, userLevel);
//                if (!matchLevel) {
//                    ToastUtil.show("等级不足");
//                    return;
//                }
//            }
            IMAddCircleMsg imAddCircleMsg = new IMAddCircleMsg(context, circleId);
            imAddCircleMsg.show();
        }
    }

    @Override
    public boolean isCircleDisturb(long chatGroupId) {
        IMUserEntity user = getUser(chatGroupId);
        return user != null && user.getNoDisturb();
    }


    @Override
    public void addCircle(final long groupId, BaseResponseCallBack callBack) {
        getGroup(groupId, callBack);
    }

    @Override
    public List<IMUserEntity> getGroupListFriends(long uid) {
        return userRepo.getGroupListFriends(uid);
    }


    @Override
    public void updateCircleMemberCount(long groupId, int size) {
        IMUserEntity user = getUser(groupId);
        if (user != null) {
            user.setGroupCount(size);
            userRepo.updateUser(user);
        }
    }

    @Override
    public void updateCircleInfo(int groupId, long uidInt, String name, String desc) {
        IMUserEntity user = getUser(groupId);
        if (user != null) {
            user.setName(name);
            userRepo.updateUser(user);
        }


    }

    @Override
    public String getJoinBtnStr(ICircleEntry item) {
        String btnStr = "加入";
        if (item.getJoinState()) {
            btnStr = "已加入";
        }
        return btnStr;
    }

    @Override
    public void addCircleMember(List<CircleMemberResponse> circleMemberResponses) {
        if (circleMemberResponses == null || circleMemberResponses.size() == 0) {
            return;
        }
        long chatGroupId = circleMemberResponses.get(0).getChatGroupId();

        List<CircleMember> circleMembers = userRepo.getCircleMembers(chatGroupId, AccountHelper.getUidInt());
        Map<Long, CircleMember> groupMap = new HashMap<>(9);
        for (CircleMember entity : circleMembers) {
            groupMap.put(entity.getUserId(), entity);
        }
        for (CircleMemberResponse tUser : circleMemberResponses) {
            CircleMember circleMember = new CircleMember();
            circleMember.setGroupId(chatGroupId);
            circleMember.setRemarkName(tUser.getRemarkName());
            circleMember.setUserId(tUser.getUserId());
            circleMember.setWhoId(AccountHelper.getUidInt());
            userRepo.addCircleMember(AccountHelper.getUidInt(), circleMember);

            IMUserEntity user = userRepo.getUser(AccountHelper.getUidInt(), tUser.getUserId(), Params.USER_PERSON);
            String tUserName = tUser.getName();
            String tUserAvator = tUser.getAvatar();
            //用户等级
            int tGroupId = tUser.getGrade();
            if(user == null){
                IMUserEntity IMUserEntity = new IMUserEntity();
                IMUserEntity.setUserId(tUser.getUserId());
                IMUserEntity.setAvatarPath(tUserAvator);
                IMUserEntity.setWhoId(AccountHelper.getUidInt());
                IMUserEntity.setName(tUserName);
                IMUserEntity.setType(Params.USER_PERSON);
                IMUserEntity.setUserLevel(tGroupId);
                IMUserEntity.setDate(tUser.getRegistrationTime());
                userRepo.addUser(IMUserEntity);
            }else{
                //更新用户信息
                if (!TextUtils.isEmpty(tUserName)) {
                    if (!user.getName().equals(tUserName)) {
                        user.setName(tUserName);
                    }
                }
                if (!TextUtils.isEmpty(tUserAvator)) {
                    if (!user.getAvatarPath().equals(tUserAvator)) {
                        user.setAvatarPath(tUserAvator);
                    }
                }
                if (tGroupId != 0) {
                    if (user.getUserLevel() != tGroupId) {
                        user.setUserLevel(tGroupId);
                    }
                }
                userRepo.updateUser(user);
            }
            groupMap.remove(tUser.getUserId());
        }

        if (groupMap.size() > 0) {
            for (Map.Entry<Long, CircleMember> entry : groupMap.entrySet()) {
                LogUtils.i("author" + "群组成员数据记录删除：" + entry.getValue().toString());
                userRepo.deleteCircleMember(entry.getValue().getId());
            }
        }
    }

    @Override
    public CircleMember getCircleMember(long userId, long chatGroupId) {
        return userRepo.getCircleMember(AccountHelper.getUidInt(), userId, chatGroupId);
    }

    @Override
    public IMUserEntity getUser(long mCircleId) {
        return domainCommonManger.getUser(mCircleId, Params.USER_GROUP);
    }

    @Override
    public List<IMUserEntity> getGroupListMyGroupFirst(long uidInt) {
        return userRepo.getGroupListMyGroupFirst(uidInt);
    }


    @Override
    public String getCircleRemarkName(long mCircleId) {
        CircleMember circleMember = getCircleMember(AccountHelper.getUidInt(), mCircleId);
        if(circleMember != null && !TextUtils.isEmpty(circleMember.getRemarkName())){
            return circleMember.getRemarkName();
        }
        return "";
    }

    @Override
    public void updateMyCircleRemarkName(long mCircleId, String remarkName) {
        CircleMember circleMember = getCircleMember(AccountHelper.getUidInt(), mCircleId);
        if(circleMember != null){
            circleMember.setRemarkName(remarkName);
            userRepo.updateCircleMember(circleMember);
        }

    }

    @Override
    public String getCircleRemarkName(IMUserEntity iMUserEntity, long chatGroupId) {
        return getCircleRemarkName(iMUserEntity.getUserId(), chatGroupId, iMUserEntity.getName(), iMUserEntity.getRemarkName());
    }

    @Override
    public String getCircleRemarkName(long userId, long chatGroupId, String name, String remarkName) {
        return domainCommonManger.getCircleRemarkName(userId, chatGroupId, name, remarkName);
    }

    @Override
    public void setNoDisturb(long mCircleId, boolean checked) {
        IMUserEntity circleEntity = getUser(mCircleId);
        if(circleEntity != null){
            circleEntity.setNoDisturb(checked);
            userRepo.updateUser(circleEntity);
        }
    }


    @Override
    public Notice getNoticeInMem(long toUserId) {
        return noticeMap.get(toUserId);
    }

    @Override
    public void putNoticeInMem(Notice result, long circleId) {
        noticeMap.put(circleId, result);
    }

    /**
     * 先保存在内存中先，后面改成数据库读取和socket同步备注名
     * @param mContext
     * @param mCircleId
     * @param action
     */
    @Override
    public void getCircleMemberResponse(Context mContext, final long mCircleId, boolean needUpdate, final Action1 action) {
        if(action == null){
            return;
        }
        if(circleMemberMap.get(mCircleId) == null || needUpdate){
            RetrofitFactory.getRetrofit().create(CircleMemberApi.class)
                    .getCircleMembers(mCircleId, AccountHelper.getUidInt())
                    .compose(RxUtil.<BaseImResponse<List<CircleMemberResponse>>>rxSchedulerHelper())
                    .compose(RxUtil.<List<CircleMemberResponse>>commonResult())
                    .compose(((RxAppCompatActivity)mContext).<List<CircleMemberResponse>>bindToLifecycle())
                    .subscribe(new CommonSubscriber<List<CircleMemberResponse>>(mContext) {

                        @SuppressLint("DefaultLocale")
                        @Override
                        public void onNext(List<CircleMemberResponse> circleMemberResponses) {
                            circleMemberMap.put(mCircleId, circleMemberResponses);
                            action.call(circleMemberResponses);
                        }
                    });
        }else {
            action.call(circleMemberMap.get(mCircleId));
        }


    }

    @Override
    public String getTagConvert(String content, long chatGroupId) {
        return domainCommonManger.getTagConvert(content, chatGroupId);
    }


}
